/*
 * @(#)NotifyEmailArchiveAction.java
 *
 * Copyright (c) 2005 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.rules.action;

import java.sql.Connection;
import java.sql.Timestamp;

import org.mandarax.eca.ActionException;

import com.dcivision.alert.bean.MtmUpdateAlertRecipient;
import com.dcivision.alert.bean.UpdateAlert;
import com.dcivision.alert.bean.UpdateAlertSystemLog;
import com.dcivision.alert.bean.UpdateAlertType;
import com.dcivision.alert.core.AlertManager;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.EmailMessageToRule;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.GenericAddress;
import com.dcivision.framework.notification.EmailDeliveryMessage;
import com.dcivision.framework.notification.NotificationWay;
import com.dcivision.framework.notification.NotificationWayFactory;
import com.dcivision.mail.bean.EmailMessageImpl;
import com.dcivision.rules.RuleOperationConstant;
import com.dcivision.user.bean.UserRecord;


/**
 * <p>Class Name:  NotifyEmailArchiveAction </p>
 * <p>Description: This class will notify message .</p>
 * 
 * @author         Beyond Qu
 * @company        DCIVision Limited
 * @creation date  05/08/2005
 * @version        $Revision: 1.16.4.1 $
 */
public class NotifyEmailArchiveAction extends AbstractRuleAction {
	  
  public static final String REPLACESTR = "VVVVVV";
  
  private String ruleDescription;
  
  /**
   * Constructor.
   */
  public NotifyEmailArchiveAction() {
    super();
  }

  /**
   * Perform an action.
   * @param param the action parameters
   */
  public void perform(Object[] param) throws ActionException {
	  
    log.debug("================= NotifyEmailArchiveAction perform Start====================");
    Connection dbConn = null;
    try{
      dbConn = DataSourceFactory.getConnection();
      SessionContainer sessionContainer = this.getSessionContainer();

      // get the location information
      String locationStr = (String)this.getTarget();
      String notifyType = "";      
      notifyType = TextUtility.replaceString(locationStr,RuleOperationConstant.SPLIT_STRING,",");
      
//      String[] locationArr = TextUtility.splitString(locationStr,RuleOperationConstant.SPLIT_STRING);      
//      String notifyType = "";
//      if(Utility.isEmpty(locationArr)){
//       if(){
//         notifyType = locationArr[0]+","+locationArr[1];         
//       } else {
//         notifyType = locationArr[0]+","+locationArr[1];
//       } 
//      }


      
      //get the message bean
      EmailMessageImpl emailMessage =  EmailMessageImpl.newInstance();
      EmailMessageToRule emailMessageToRule = (EmailMessageToRule)param[0];
      emailMessage.setEmailMessageData(emailMessageToRule);

      
      //set user
      UserRecord tmpUserRecord = new UserRecord();
      tmpUserRecord.setID(new Integer(1));
      sessionContainer.setUserRecord(tmpUserRecord);
      sessionContainer.setByPassPermission(true);
      sessionContainer.setUserIPAddress("127.0.0.1");      
      
      

      //  is private ,send message once
      if(emailMessageToRule.getIsPrivaeteRule()){
        insertReminderNotification(sessionContainer,dbConn,emailMessage,param,notifyType,emailMessageToRule.getMessgeUserID());        
      }//is public ,send multi send messages
      else{
        if(!Utility.isEmpty(emailMessageToRule.getToUserIDStr())){
          String[] userIDArr = TextUtility.splitString(emailMessageToRule.getRuleCreatorIDStr(),",");
          for(int i = 0 ; i< userIDArr.length ;i++ ){
            Integer userID = TextUtility.parseIntegerObj(userIDArr[i]);
            if(!Utility.isEmpty(userID)){
              insertReminderNotification(sessionContainer,dbConn,emailMessage,param,notifyType,userID);        
            }            
          }
        }
      } 

    
      dbConn.commit();
    } catch (ApplicationException appEx) {
      log.debug(" Application Exception :", appEx);
      log.error(appEx, appEx);
    } catch (Exception e) {
     log.debug(" Trigger a workflow occur Fatal Error.");
     log.error(e, e);      
    } finally {
      try { dbConn.close(); } catch (Exception ignore) {} finally { dbConn = null; }
    }
    log.debug("================= NotifyEmailArchiveAction perform End ====================");    
  }
/**
 * 
 * @param emailMessage
 * @param kbFileName
 * @param ruleType
 * @return
 */
  private String makeMessageBody(EmailMessageImpl emailMessage, String kbFileName, String ruleType) {
    String messageBody;
    String from = replaceEspecialChar(emailMessage.getSender());
    String to = replaceEspecialChar(emailMessage.getTo());
    String subject = replaceEspecialChar(emailMessage.getSubject());
//    String emailID = replaceEspecialChar(emailMessage.getMessageID());
    String cc = replaceEspecialChar(emailMessage.getCc());
//    String attachmentNum= String.valueOf(emailMessage.getAttachments().size());

    String ruleName = replaceEspecialChar(this.getRuleName());
    String ruleDesc = replaceEspecialChar(this.getRuleDescription());
    String ruleType2 =replaceEspecialChar(ruleType);
    String ruleKBFileName = replaceEspecialChar(kbFileName);
    /**String ruleType ="";
    String ruleName = "";
    String ruleDesc = "";
    String action =  "";
    String conditionName =  "";
    String conditionValue = "";
    String conditionPredicate =  "";
    
    if(!Utility.isEmpty(ruleInfo)){
       ruleType =replaceEspecialChar((String)ruleInfo.get("ruleType"));
       ruleName = replaceEspecialChar((String)ruleInfo.get("ruleName"));
       ruleDesc = replaceEspecialChar((String)ruleInfo.get("ruleDesc"));
       action =  replaceEspecialChar((String)ruleInfo.get("action"));
       conditionName = replaceEspecialChar((String)ruleInfo.get("conditionName"));
       conditionValue = replaceEspecialChar((String)ruleInfo.get("conditionValue"));
       conditionPredicate =  replaceEspecialChar((String)ruleInfo.get("conditionPredicate"));
    }
    //"from|to,cc|subject|emailID|ruleType|ruleName|ruleDesc|conditionName|conditionPredicate|conditionValue|action|cc|a"
    messageBody = from+"|"+to+"|"+subject+"|"+emailID+"|"+ruleType+"|"+ruleName+"|"
                  +ruleDesc+"|"+conditionName+"|"+conditionPredicate+"|"+conditionValue+"|"+action+"|"+cc+"|"+attachmentNum;
    */
    //from|to,cc|subject|ruleType|ruleName|ruleDesc|ruleKBFileName
    messageBody = from+"|"+to+","+cc+"|"+subject+"|"+ruleType2+"|"+ruleName+"|"+ruleDesc+"|"+ruleKBFileName;
    return messageBody;
  }

  private String replaceEspecialChar(String inputStr) {
    String outStr="";
    if(!Utility.isEmpty(inputStr)){
      outStr = inputStr;
      if(inputStr.indexOf("|")!=-1){
        outStr=inputStr.replaceAll("\\|", REPLACESTR);
      }
    }
    return outStr;
  }
  
  public void insertReminderNotification(SessionContainer sessionContainer, Connection conn ,EmailMessageImpl emailMessage,Object[] param,String notificationWay,Integer userID) throws ApplicationException  {
    DmsDocument document = new DmsDocument();
    
    // message body
//    HashMap ruleInfo =null;
    String  kbFileName = "";
    String  ruleType = "";
    if(param.length>=3&&!Utility.isEmpty(param[1])){
      kbFileName=(String)param[1];
      ruleType=(String)param[2];
    }

    String messageBody  = makeMessageBody(emailMessage,kbFileName, ruleType);
    
    //send system message
    if (notificationWay.indexOf("S") != -1) {    
      UpdateAlert updateAlert = new UpdateAlert();
      updateAlert.setObjectType(UpdateAlert.EMAIL_ARCHIVE_TYPE);
      updateAlert.setObjectID(document.getID());
      AlertManager alertManager = new AlertManager(sessionContainer, conn);
      
      Timestamp targetSrcTime = Utility.getCurrentTimestamp();
      String reminderType = "B";
      int reminderAmount = 0;
      Integer versionID = document.getVersionID();
      
      UpdateAlert newUpdateAlert=alertManager.createUpdateAlert(updateAlert, UpdateAlert.EMAIL_ARCHIVE_TYPE);
      
      UpdateAlertType updateAlertType = new UpdateAlertType();
      updateAlertType.setUpdateAlertID(newUpdateAlert.getID());
//    updateAlertType.setActionType(UpdateAlert.REMIND_ACTION);
      updateAlertType.setActionType(UpdateAlert.EMAIL_ARCHIVE_EMAIL_RECIVE_ACTION);    
      updateAlertType.setNotifyWay(notificationWay);
      updateAlertType.setMessage(messageBody);
      updateAlertType = alertManager.createAlertUpdateType(updateAlertType);
      
      UpdateAlertSystemLog updateAlertSystemLog = new UpdateAlertSystemLog();
      updateAlertSystemLog.setUpdateAlertTypeID(updateAlertType.getID());
      updateAlertSystemLog.setActionUserID(userID);
      updateAlertSystemLog.setRecordStatus(GlobalConstant.STATUS_ACTIVE);
//    updateAlertSystemLog.setRecordStatus(GlobalConstant.STATUS_INACTIVE);       
      
      updateAlertSystemLog.setActionDate(targetSrcTime);
      updateAlertSystemLog.setVersionID(versionID);
      updateAlertSystemLog = alertManager.createSystemLog(updateAlertSystemLog);
      
      MtmUpdateAlertRecipient recipient = new MtmUpdateAlertRecipient();
      recipient.setUpdateAlertID(newUpdateAlert.getID());
      recipient.setRecipientType(UpdateAlert.USER_RECIPIENT);
      recipient.setRecipientID(userID);
      alertManager.createUpdateAlertRecipient(newUpdateAlert, updateAlertType, recipient);
    }
   try{
     // send email message
    if (notificationWay.indexOf("E") != -1) {	   
      EmailDeliveryMessage msg = new EmailDeliveryMessage();
//    boolean bNeedNotify = false;

      String curUserEmail = UserInfoFactory.getUserEmailAddress(userID);
      String curUserName = UserInfoFactory.getUserFullName(userID);
      msg.addToRecipient(new GenericAddress(curUserEmail, curUserName));        
//      msg.setSender(new GenericAddress(curUserEmail, curUserName));    
      msg.setSender(new GenericAddress(SystemParameterFactory.getSystemParameter(SystemParameterConstant.SMTP_ADMIN_ADDRESS)
          ,SystemParameterFactory.getSystemParameter(SystemParameterConstant.SMTP_ADMIN_NAME)));          
      msg.setSubject("Email Archive Notification");    

      StringBuffer content = makeEmailContent(emailMessage, curUserName,ruleType);        
    
      msg.setMailContent(content.toString());
      NotificationWay emailNotification = NotificationWayFactory.getNotificationInstance(NotificationWay.EMAIL_NOTIFICATION_INSTANCE);
      emailNotification.addDeliveryMessage( msg);
      emailNotification.send();
    }    
   }catch(Exception e){
	   
   }
    
    //this.commit(request);
    //conn.commit() ;
  }

  /**
   * @param messageBody
   * @param curUserName
   * @param ruleType 
   * @return
   */
  private StringBuffer makeEmailContent(EmailMessageImpl emailMessage, String curUserName, String ruleType) {

    StringBuffer content = new StringBuffer();
    content.append("Dear "+curUserName+", \n\n");
//      content.append("It is to notify you that you receive a email . \n\n");
    content.append("An Email is received .\n");
    content.append("\n\n");
    //email info
    content.append("<table><tr><td>Subject :</td><td>").append(emailMessage.getSubject()).append("</td></tr>");
    content.append("<tr><td>Sender:</td><td>").append(emailMessage.getSender()).append("</td></tr>");
    content.append("<tr><td>Recipient:</td><td>").append(emailMessage.getTo()).append("</td></tr></table>");
    content.append("\n\n");
    //rule info
    content.append("<table><tr><td>Matched Rule Name :</td><td>").append(this.getRuleName()).append("</td></tr>");
    content.append("<tr><td>RuleType:</td><td>").append(ruleType).append("</td></tr>");
    content.append("<tr><td>Description:</td><td>").append(this.getRuleDescription()).append("</td></tr></table>");
    
    content.append("\n\n");
    content.append("Thanks.\n\n");
    return content;
  }

  public String getRuleDescription() {
    return ruleDescription;
  }

  public void setRuleDescription(String ruleDescription) {
    this.ruleDescription = ruleDescription;
  }
	    
}
